package com.nave.segundaguerra.game;

import java.util.ArrayList;
import java.util.List;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class Animation 
{
	public List<uniqueAnimation> allAnimations;
	
	protected uniqueAnimation currentAnimation;
	
	protected Bitmap currentImageDraw;
	public Rect currentRect;
	protected boolean runnable;
	protected int count;
	protected int currentFrame;
	
	public Animation(Bitmap image,Rect rect)
	{
		currentImageDraw = image;
		currentRect = rect;
		allAnimations = new ArrayList<uniqueAnimation>();
	}

	public void Play()
	{
		runnable = true;
	}
	
	public void clearState()
	{
		currentFrame = 0;
		count = 0;
	}
	
	public void Update() 
	{
		if(runnable)
		{
			count ++;
			
			if(count > currentAnimation.timeRating)
			{
				count = 0;
					
				currentFrame++;
					
				if(currentFrame > currentAnimation.Sprites.length-1)
				{
					switch(currentAnimation.animationType)
					{
						case LOOP:
							clearState();
							break;
						case ONCE:
							clearState();
							currentImageDraw = null;
							runnable = false;
							return;
					}
				}
				
				currentImageDraw = currentAnimation.Sprites[currentFrame];
			}

		}
	}
	
	public void switchFrame(int index)
	{
		if(currentAnimation != null)
		currentImageDraw = currentAnimation.Sprites[index];
	}
	
	public void StartAnimation(String animationName)
	{
		if(currentAnimation != null)
		{
			if(animationName != currentAnimation.animationName)
			{
				for(uniqueAnimation i : allAnimations)
				{
					if(i.animationName == animationName)
					{
						currentAnimation = i;
						clearState();
						Play();
						break;
					}
				}
			}
		}
		else
		{
			for(uniqueAnimation i : allAnimations)
			{
				if(i.animationName == animationName)
				{
					currentAnimation = i;
					clearState();
					Play();
					break;
				}
			}
		}
	}
	
	public void Draw(Canvas canvas,Rect rect)
	{
		if(currentImageDraw != null)
		canvas.drawBitmap(currentImageDraw,currentRect, rect, new Paint());
	}
	
}

